import React, { useState } from 'react';
import { Progress, Card, Typography, Timeline, Tag, Space, Button } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, SyncOutlined } from '@ant-design/icons';
import { useSpecificTaskProgress } from '../../hooks/useTaskProgress';
import type { TaskProgressInfo, MilestoneInfo } from '../../utils/TaskProgressWebSocketClient';

const { Title, Text } = Typography;

interface TaskProgressMonitorProps {
  taskId: number;
  onProgressUpdate?: (progress: TaskProgressInfo) => void;
}

/**
 * 任务进度监控组件
 * 实时显示任务执行进度和里程碑信息
 */
export const TaskProgressMonitor: React.FC<TaskProgressMonitorProps> = ({ 
  taskId, 
  onProgressUpdate 
}) => {
  const { isConnected, progress } = useSpecificTaskProgress(taskId);
  const [isExpanded, setIsExpanded] = useState(false);

  // 获取进度条颜色
  const getProgressColor = (progress: number, isMilestone: boolean) => {
    if (isMilestone) return '#52c41a'; // 绿色，表示里程碑
    if (progress >= 80) return '#1890ff'; // 蓝色
    if (progress >= 50) return '#faad14'; // 橙色
    return '#ff4d4f'; // 红色
  };

  // 格式化剩余时间
  const formatRemainingTime = (seconds: number) => {
    if (seconds < 60) return `${seconds}秒`;
    if (seconds < 3600) return `${Math.floor(seconds / 60)}分${seconds % 60}秒`;
    return `${Math.floor(seconds / 3600)}小时${Math.floor((seconds % 3600) / 60)}分钟`;
  };

  // 获取阶段显示名称
  const getStageDisplayName = (stage: string) => {
    const stageMap: { [key: string]: string } = {
      'INITIALIZATION': '初始化',
      'CONFIG_VALIDATION': '配置验证',
      'GIT_CLONE_START': '开始下载代码',
      'GIT_CLONING': '正在下载代码',
      'GIT_CLONE_COMPLETE': '代码下载完成',
      'CODE_SCANNING': '扫描源码文件',
      'SQL_EXTRACTION_START': '开始SQL提取',
      'SQL_PARSING': '解析SQL语句',
      'SQL_EXTRACTION_COMPLETE': 'SQL提取完成',
      'SQL_SAVING': '保存SQL语句',
      'RULE_ANALYSIS_START': '开始规则分析',
      'RULE_LOADING': '加载兼容性规则',
      'RULE_MATCHING': '匹配规则模式',
      'RULE_RESULT_PROCESSING': '处理规则结果',
      'RULE_ANALYSIS_COMPLETE': '规则分析完成',
      'AI_PREPARATION': 'AI验证准备',
      'AI_DATA_SAVING': '保存规则结果',
      'AI_VERIFICATION_START': '开始AI验证',
      'AI_BATCH_PROCESSING': 'AI批量验证',
      'AI_VERIFICATION_COMPLETE': 'AI验证完成',
      'RESULT_AGGREGATION': '聚合分析结果',
      'RESULT_SAVING': '保存最终结果',
      'STATISTICS_UPDATE': '更新统计信息',
      'CLEANUP': '清理临时文件',
      'COMPLETION': '任务完成'
    };
    return stageMap[stage] || stage;
  };

  // 调用外部回调
  React.useEffect(() => {
    if (progress && onProgressUpdate) {
      onProgressUpdate(progress);
    }
  }, [progress, onProgressUpdate]);

  if (!progress) {
    return (
      <Card>
        <Space>
          {isConnected ? (
            <>
              <SyncOutlined spin />
              <Text>等待任务进度信息...</Text>
            </>
          ) : (
            <>
              <PauseCircleOutlined />
              <Text type="danger">WebSocket连接断开</Text>
            </>
          )}
        </Space>
      </Card>
    );
  }

  return (
    <Card
      title={
        <Space>
          <Title level={5} style={{ margin: 0 }}>
            任务进度 #{taskId}
          </Title>
          {isConnected ? (
            <Tag color="success">已连接</Tag>
          ) : (
            <Tag color="error">连接断开</Tag>
          )}
        </Space>
      }
      extra={
        <Button
          type="text"
          size="small"
          onClick={() => setIsExpanded(!isExpanded)}
        >
          {isExpanded ? '收起' : '展开详情'}
        </Button>
      }
    >
      {/* 主要进度信息 */}
      <Space direction="vertical" style={{ width: '100%' }}>
        <div>
          <Space>
            <Text strong>当前阶段：</Text>
            <Tag color="blue">{getStageDisplayName(progress.currentStage)}</Tag>
            {progress.isMilestone && (
              <Tag color="gold" icon={<PlayCircleOutlined />}>
                里程碑
              </Tag>
            )}
          </Space>
        </div>

        {/* 进度条 */}
        <Progress
          percent={progress.progress}
          status={progress.progress === 100 ? 'success' : 'active'}
          strokeColor={getProgressColor(progress.progress, progress.isMilestone || false)}
          format={(percent) => (
            <span style={{ color: '#000' }}>
              {percent}%
            </span>
          )}
        />

        {/* 当前状态消息 */}
        <Text>{progress.message}</Text>

        {/* 预估剩余时间 */}
        {progress.estimatedRemainingSeconds && progress.estimatedRemainingSeconds > 0 && (
          <Text type="secondary">
            预估剩余时间: {formatRemainingTime(progress.estimatedRemainingSeconds)}
          </Text>
        )}

        {/* 里程碑信息 */}
        {progress.isMilestone && progress.milestoneTitle && (
          <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
            <Space direction="vertical">
              <Text strong style={{ color: '#389e0d' }}>
                🎯 {progress.milestoneTitle}
              </Text>
              {progress.milestoneDescription && (
                <Text>{progress.milestoneDescription}</Text>
              )}
            </Space>
          </Card>
        )}

        {/* 展开的详细信息 */}
        {isExpanded && (
          <>
            {/* 统计信息 */}
            {progress.statistics && Object.keys(progress.statistics).length > 0 && (
              <Card size="small" title="统计信息" style={{ marginTop: 16 }}>
                <Space direction="vertical" size="small">
                  {Object.entries(progress.statistics).map(([key, value]) => (
                    <div key={key}>
                      <Text strong>{key}: </Text>
                      <Text>{String(value)}</Text>
                    </div>
                  ))}
                </Space>
              </Card>
            )}

            {/* 已完成的里程碑 */}
            {progress.completedMilestones && progress.completedMilestones.length > 0 && (
              <Card size="small" title="已完成里程碑" style={{ marginTop: 16 }}>
                <Timeline>
                  {progress.completedMilestones.map((milestone: MilestoneInfo, index: number) => (
                    <Timeline.Item
                      key={index}
                      color="green"
                    >
                      <Space direction="vertical" size="small">
                        <Text strong>{milestone.title}</Text>
                        {milestone.description && (
                          <Text type="secondary">{milestone.description}</Text>
                        )}
                        <Text type="secondary">
                          完成时间: {new Date(milestone.completedAt).toLocaleString()}
                        </Text>
                      </Space>
                    </Timeline.Item>
                  ))}
                </Timeline>
              </Card>
            )}

            {/* 调试信息 */}
            <Card size="small" title="调试信息" style={{ marginTop: 16 }}>
              <Space direction="vertical" size="small">
                <Text>时间戳: {new Date(progress.timestamp).toLocaleString()}</Text>
                <Text>WebSocket状态: {isConnected ? '已连接' : '断开'}</Text>
              </Space>
            </Card>
          </>
        )}
      </Space>
    </Card>
  );
};

export default TaskProgressMonitor;